package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author wyh
 * @Date 2025/3/19 13:36
 * @description: 获取锁的实现
 *
 * 通过使用 Lua 脚本、锁的续期机制、合理设置锁的过期时间，
 */
public class SimpleRedisLock implements ILock {
    //用户传递的值
    private StringRedisTemplate stringRedisTemplate;
    private String name;
    private static final String LOCK_PREFIX = "LOCK:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";// 线程的标识，确保集群下唯一，防止误删其他线程的锁
    private static final DefaultRedisScript<Long> UNLOCK_LUA_SCRIPT;
    static {
        UNLOCK_LUA_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_LUA_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_LUA_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        // 线程的标识，确保集群下唯一，防止误删其他线程的锁
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁,返回是Boolean类型，有拆箱动作，可能返回是null，避免空指针异常
        // name保证锁粒度，只对同一个用户加锁
        Boolean isSuccess = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(isSuccess);
    }

    @Override
    public void unlock() {
        //调用lua脚本，获取锁、判断锁、删除锁是原子操作
        stringRedisTemplate.execute(
                UNLOCK_LUA_SCRIPT,
                Collections.singletonList(LOCK_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
    /*
    @Override
    //获取锁、判断锁、删除锁不是原子操作，需要使用Lua脚本保证操作的原子性
    public void unlock() {
        String getlock = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
        String actuallock = ID_PREFIX + Thread.currentThread().getId();
        // 释放锁，判断是否为当前线程加的锁
        if (getlock.equals(actuallock)) {
            // 当前线程，删除锁
            stringRedisTemplate.delete(LOCK_PREFIX + name);
        }*/
